/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.core.param;

import com.alibaba.fastjson.JSONObject;
import com.jfast.framework.kit.StrKit;
import com.jfast.framework.orm.TypeConvert;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Bean对象注入
 * @author zengjintao
 * @version 1.0
 * @createTime 2018年7月11日下午1:29:45
 */
public class BeanParam extends RequestMappingMethodParam {
	
	private Class<?> beanClass;

	public BeanParam(HttpServletRequest request, Class<?> beanClass) {
		super(request);
		this.beanClass = beanClass;
	}

	public void setBeanClass(Class<?> beanClass) {
		this.beanClass = beanClass;
	}

	@Override
	Object doGetBean(Map<String, String[]> params) {
		String modelName = StrKit.toLowerCaseFirst(beanClass.getSimpleName());
		Object object = classFactory.createBean(beanClass);
		for (Map.Entry<String, String[]> entry : params.entrySet()) {
			String paraKey = entry.getKey();
			if (paraKey.startsWith(modelName + ".")) {
				String fieldName = paraKey.substring(paraKey.lastIndexOf(".") + 1, paraKey.length());
				try {
					Field field = beanClass.getDeclaredField(fieldName);
					Class<?> clazzType = field.getType();
					field.setAccessible(true);
					if (entry.getValue().length == 1) {
						Object convertValue = TypeConvert.convert(clazzType, entry.getValue()[0]);
						field.set(object, convertValue);
					}
					else if (entry.getValue().length > 1) {
						field.set(object, StringUtils.join(entry.getValue(), ","));
					}
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return object;
	}

	@Override
	Object doGetBeanByJson(String requestBody) {
		return JSONObject.parse(requestBody);
	}
}
